<?php

class AutocompleteController extends Zend_Controller_Action
{
       
        
	public function indexAction(){
		$this->_helper->viewRenderer->setNoRender();
	}

	
	public function getNomeRedeAction(){
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
		
		echo json_encode($this->autocomplete($this->getParam('term'), new DbTable_RedeMercado(), 'nm_rede_mercado'));
	}
	
	
	public function getNomeMercadoAction(){
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
	
		echo json_encode($this->autocomplete($this->getParam('term'), new DbTable_Mercado(), 'nm_mercado'));
	}
	
	

	public function getLogradouroAction(){
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
	
		echo json_encode($this->autocomplete($this->getParam('term'), new DbTable_Endereco(), 'nm_logradouro'));
	}
	
	
	public function getBairroAction(){
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
	
		echo json_encode($this->autocomplete($this->getParam('term'), new DbTable_Endereco(), 'nm_bairro'));
	}
	
	
	public function getCidadeAction(){
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
	
		echo json_encode($this->autocomplete($this->getParam('term'), new DbTable_Localidade(), 'nm_cidade'));
	}
	
        
        public function getProdutoAction(){
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();

            echo json_encode($this->autocomplete($this->getParam('term'), new DbTable_Produto(), 'nm_produto'));
	}
        
        public function getFabricanteAction(){
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();

            echo json_encode($this->autocomplete($this->getParam('term'), new DbTable_Produto(), 'nm_fabricante'));
	}      
        
        public function getDescricaoAction(){
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();

            echo json_encode($this->autocomplete($this->getParam('term'), new DbTable_Produto(), 'ds_produto'));
	}         
        
        
	private function autocomplete($term, $dbTable, $column){
		
		$term = strtoupper($term);
		$column = strtolower($column);
		
		$select = $dbTable->select()
					->from($dbTable, "DISTINCT ({$column})")
					->where("{$column} like '%{$term}%'")
					->order("{$column} asc");
		
		$objects = $dbTable->fetchAll($select);
		
		$results = array();
		
		foreach ($objects as $object) {
			array_push($results, $object->$column);
		}
		
		return $results;
	}
	
	
}

